package com.mls.guardian.protocol;


import com.mls.guardian.common.RemoteCommandType;
import com.mls.guardian.common.SerializationUtils;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by jl on 15/9/8.
 */
public class RemoteCommand implements Serializable {
    private int code;
    private RemoteCommandType remoteCommandType;
    private String clientId;
    private RemoteBody remoteBody;
    private  int flag = 0;  //2是oneway方式


    private static AtomicInteger RequestIdAtomic = new AtomicInteger(0);
    private int requestId = RequestIdAtomic.incrementAndGet();
    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public RemoteBody getRemoteBody() {
        return remoteBody;
    }

    public void setRemoteBody(RemoteBody remoteBody) {
        this.remoteBody = remoteBody;
    }

    public static ByteBuffer encode(RemoteCommand remoteCommand) throws IOException {
        int length = 4;//头长度

        byte body[] = SerializationUtils.H2Serialize(remoteCommand);

//        byte body[] = str.getBytes(Charset.forName("UTF-8"));

        ByteBuffer result = ByteBuffer.allocate(length+body.length);
        result.putInt(body.length);

        result.put(body);

        result.flip();

        return result;
    }

    public static RemoteCommand decode(byte[] body){
        RemoteCommand remoteCommand = null;
        try {
            remoteCommand = (RemoteCommand) SerializationUtils.H2Deserialize(body, RemoteCommand.class);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return remoteCommand;
    }
    public static String toStr(){
        return "";
    }

    public int getRequestId() {
        return requestId;
    }

    public void setRequestId(int requestId) {
        this.requestId = requestId;
    }

    public static void main(String a[]){
        ByteBuffer result = ByteBuffer.allocate(10);
        result.putInt(10);
        result.flip();

        System.out.println(result.limit());
    }

    public void addRequest(){
        this.requestId =  RequestIdAtomic.getAndIncrement();
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }


    public RemoteCommandType getRemoteCommandType() {
        return remoteCommandType;
    }

    public void setRemoteCommandType(RemoteCommandType remoteCommandType) {
        this.remoteCommandType = remoteCommandType;
    }

    public void markOneway(){
        this.flag = 2;
    }

    public boolean isOneWay(){
        return this.flag == 2;
    }

}
